﻿#region Copyright(C) 2010-2010 NCS Pte. Ltd. All rights reserved.
// ==================================================================================================
// Copyright(C) 2010 NCS Pte. Ltd. All rights reserved.
//
// SYSTEM NAME	    : iConnect .Net Application Framework
// COMPONENT ID	    : NCS.IConnect.Core.Wcf
// COMPONENT DESC   : Core components for WCF.	
//
// CREATED DATE/BY  : 18 Aug 2010 / Gao Ye
//
// REVISION HISTORY :	
// DATE/BY			SR#/CS/PM#/OTHERS		DESCRIPTION OF CHANGE
// ==================================================================================================
#endregion

using NCS.IConnect.Core.Utilities;
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;


namespace NCS.IConnect.Core.ApplicationContexts.Wcf
{
    /// <summary>
    /// A custom CallContextInitializer to initialize Transaction Id.
    /// </summary>
    public class TransactionIdInitializer: ICallContextInitializer
    {
        /// <summary>
        /// Implement to participate in cleaning up the thread that invoked the operation.
        /// </summary>
        /// <param name="correlationState">The correlation object returned from the <see cref="M:System.ServiceModel.Dispatcher.ICallContextInitializer.BeforeInvoke(System.ServiceModel.InstanceContext,System.ServiceModel.IClientChannel,System.ServiceModel.Channels.Message)"/> method.</param>
        public void AfterInvoke(object correlationState)
        {
            Guard.ArgumentNotNull(correlationState, "correlationState");
            ApplicationContext.Current.TransactionId = correlationState.ToString();
        }

        /// <summary>
        /// Implement to participate in the initialization of the operation thread.
        /// </summary>
        /// <param name="instanceContext">The service instance for the operation.</param>
        /// <param name="channel">The client channel.</param>
        /// <param name="message">The incoming message.</param>
        /// <returns>
        /// A correlation object passed back as the parameter of the <see cref="M:System.ServiceModel.Dispatcher.ICallContextInitializer.AfterInvoke(System.Object)"/> method.
        /// </returns>
        public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
        {
            string originalTransactionId = ApplicationContext.Current.TransactionId;
            if (string.IsNullOrEmpty(originalTransactionId))
            {
                ApplicationContext.Current.TransactionId = Guid.NewGuid().ToString();
            }
            return originalTransactionId;
        }
    }
}